package projectsupporter.form;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.eclipse.jface.dialogs.ProgressMonitorDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CTabFolder;
import org.eclipse.swt.custom.CTabItem;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeColumn;
import org.eclipse.swt.widgets.TreeItem;

import projectsupporter.common.constant.Constant;
import projectsupporter.common.control.BannerComposite;
import projectsupporter.common.control.Path;
import projectsupporter.common.element.AddBaseCodeCompsite;
import projectsupporter.common.formbase.FolderFromWorkspaceDialog;
import projectsupporter.common.formbase.ProjectChooseDialog;
import projectsupporter.common.formbase.progrees.ProgressBarDialog;
import projectsupporter.common.logic.GlobalInfo;
import projectsupporter.common.logic.PlugLogic;
import projectsupporter.common.logic.PlugUILogic;
import projectsupporter.common.logic.PlugUILogic.ImagePath;
import projectsupporter.common.operation.ImportBaseOperation;
import projectsupporter.common.operation.LoadTableInfoOperation;
import projectsupporter.common.operation.LoadTableInfoOperation2;

import dbTools.DBToolEngine;
import dbTools.tableInfo.field.Field;
import dbTools.tableInfo.info.TableInfo;

import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.ui.plugin.AbstractUIPlugin;

public class MainForm {

	private Shell sShell = null;  //  @jve:decl-index=0:visual-constraint="11,-3"
	private Composite composite = null;
	private Group group1 = null;
	private Button load = null;
	private Text fileName = null;
	private Tree tableTree = null;
	private CTabFolder maincTabFolder = null;
	private Composite configComposite = null;
	
	private List<Control> editCtls=new ArrayList<Control>();  //  @jve:decl-index=0:
	private Group configGroup = null;
	private Button choosePRJButton = null;
	private Label label = null;
	private Text prjNametext = null;
	private Button importBaseButton = null;
	private Label label1 = null;
	private Label label2 = null;
	private Label label3 = null;
	private Label label4 = null;
	private Label label5 = null;
	private Text urlText = null;
	private Text userNameText = null;
	private Text passWordText = null;
	private Label label11 = null;
	private Button saveDBConfigbutton = null;
	private BannerComposite bannerComposite = null;
	/**
	 * This method initializes sShell
	 */
	private void createSShell() {
		GridLayout gridLayout = new GridLayout();
		gridLayout.horizontalSpacing = 0;
		gridLayout.marginWidth = 0;
		gridLayout.verticalSpacing = 0;
		gridLayout.marginHeight = 0;
		sShell = new Shell();
		sShell.setText(GlobalInfo.PLUGIN_ID);
		createBannerComposite();
		createComposite();
		sShell.setLayout(gridLayout);
		sShell.setSize(new Point(936, 675));
		setControls();
	}
	
	public void openShell(String prjName)
	{
		createSShell();

		GlobalInfo.PRJ_NAME=prjName;
		
		if(setIsEditMode()==false)
		{
			chossePrjName();
		}
		
		sShell.open();
		sShell.layout();
		load.setFocus();
		
		final Display display = Display.getDefault();
		while (!sShell.isDisposed()) {
			if (!display.readAndDispatch())
				display.sleep();
		}
	}
	private void chossePrjName() {
		ProjectChooseDialog pd=new ProjectChooseDialog(sShell);
		GlobalInfo.PRJ_NAME=pd.openDialog();
		setIsEditMode();
	}

	/**
	 * This method initializes composite	
	 *
	 */
	private void createComposite() {
		GridData gridData11 = new GridData();
		gridData11.grabExcessVerticalSpace = true;
		gridData11.widthHint = 160;
		gridData11.verticalAlignment = org.eclipse.swt.layout.GridData.FILL;
		GridLayout gridLayout2 = new GridLayout();
		gridLayout2.numColumns = 3;
		gridLayout2.horizontalSpacing = 0;
		GridData gridData = new GridData();
		gridData.heightHint = -1;
		gridData.grabExcessHorizontalSpace = true;
		gridData.horizontalAlignment = org.eclipse.swt.layout.GridData.FILL;
		gridData.verticalAlignment = org.eclipse.swt.layout.GridData.FILL;
		gridData.grabExcessVerticalSpace = true;
		composite = new Composite(sShell, SWT.CHECK);
		composite.setLayoutData(gridData);
		composite.setLayout(gridLayout2);
		composite.setToolTipText("");
		tableTree = new Tree(composite, SWT.MULTI | SWT.BORDER);
		tableTree.setLinesVisible(false);
		tableTree.setLocation(new Point(9, 63));
		tableTree.setHeaderVisible(false);
		tableTree.setSize(new Point(170, 570));
		tableTree.setLayoutData(gridData11);
		createMaincTabFolder();
		tableTree.addMouseListener(new org.eclipse.swt.events.MouseAdapter() {
			public void mouseDown(org.eclipse.swt.events.MouseEvent e) {
				
			  TreeItem[] items=tableTree.getSelection();
			  if(items!=null && items.length>0 && e.button == 3)
			  {
				  showMainMenu();
			  }
			}
		});
		tableTree.addTreeListener(new org.eclipse.swt.events.TreeAdapter() {
			public void treeExpanded(org.eclipse.swt.events.TreeEvent e) {
				System.out.println("treeExpanded()"); 
			}
		});
		TreeColumn treeColumn = new TreeColumn(tableTree, SWT.NONE);
		treeColumn.setWidth(tableTree.getSize().x);

	}
	/**
	 * This method initializes group1	
	 *
	 */
	private void createGroup1() {
		group1 = new Group(configComposite, SWT.NONE);
		group1.setLayout(null);
		group1.setText("TableFile");
		group1.setBounds(new Rectangle(5, 5, 708, 73));
		load = new Button(group1, SWT.NONE);
		load.setText("LoadFile");
		load.setLocation(new Point(578, 25));
		load.setSize(new Point(114, 28));
		fileName = new Text(group1, SWT.BORDER);
		fileName.setBounds(new Rectangle(9, 27, 560, 23));
		
		//fileName.setText(Platform.getLocation().toString());
		//fileName.setText(Platform.getInstanceLocation().toString());
		
		load.addSelectionListener(new org.eclipse.swt.events.SelectionAdapter() {
			public void widgetSelected(org.eclipse.swt.events.SelectionEvent e) {

				FileDialog fileselect=new FileDialog(sShell,SWT.SINGLE); 
	            fileselect.setFilterNames(new String[]{"*.xls","xls"}); 
	            fileselect.setFilterExtensions(new String[]{"*.xls","*.*"}); 
	            String path=fileselect.open();
	            if(path!=null)
	            {
	                fileName.setText(path);
	                
	                //new LoadTableInfoOperation2(MainForm.this,sShell,fileName.getText()).start();
	                try {
						new ProgressMonitorDialog(sShell).run(true, true,
						        new LoadTableInfoOperation(MainForm.this,fileName.getText()));
					} catch (InvocationTargetException e1) {
						e1.printStackTrace();
					} catch (InterruptedException e1) {
						e1.printStackTrace();
					}
					
	            }
			}
		});
	}
	
	public void fillTableTree(Map<String,TableInfo> tableInfoMap)
	{
		final Image tableImage = PlugUILogic.getImage(sShell.getDisplay(),ImagePath.PROP_PS);
		final Image fieldImage = PlugUILogic.getImage(sShell.getDisplay(),ImagePath.TOPIC_SMALL);
		for(Map.Entry<String,TableInfo> entry : tableInfoMap.entrySet())
		{
			String key = entry.getKey();
			TableInfo tableInfo= entry.getValue();
			
			TreeItem table=new TreeItem(tableTree,SWT.NONE);
			table.setText(tableInfo.getTableName());
			table.setData(Constant.ITEM_TYPE, Constant.ITEM_TYPE_TABLE);
			table.setData(Constant.TABLE_KEY, tableInfo.getKey());
			table.setImage(tableImage);
			
			Map<String,Field> fieldsMap=tableInfo.getAllFields();
			if(fieldsMap.size()==0)
			{
				fieldsMap=tableInfo.getKeyFields();
			}
			
			for(Map.Entry<String,Field> fieldEntry : fieldsMap.entrySet())
			{
				String filedDey = fieldEntry.getKey();
				Field field= fieldEntry.getValue();
				
				TreeItem fieldItem=new TreeItem(table,SWT.NONE);
				fieldItem.setText(field.getItemName());
				fieldItem.setData(Constant.ITEM_TYPE, Constant.ITEM_TYPE_Field);
				fieldItem.setData(Constant.TABLE_KEY, tableInfo.getKey());
				fieldItem.setData(Constant.Field_KEY, field.getFieldName());
				fieldItem.setImage(fieldImage);
			}
			
			
		}
	}
	/**
	 * This method initializes maincTabFolder	
	 *
	 */
	private void createMaincTabFolder() {
		GridData gridData2 = new GridData();
		gridData2.verticalAlignment = org.eclipse.swt.layout.GridData.FILL;
		gridData2.horizontalAlignment = org.eclipse.swt.layout.GridData.FILL;
		gridData2.grabExcessHorizontalSpace = true;
		gridData2.horizontalIndent = 5;
		gridData2.grabExcessVerticalSpace = true;
		maincTabFolder = new CTabFolder(composite, SWT.NONE|SWT.CLOSE|SWT.BORDER);
		createConfigComposite();
		
		maincTabFolder.setTabHeight(20);   
		maincTabFolder.setUnselectedCloseVisible(true);   

		maincTabFolder.setLayoutData(gridData2);
		 //下面是设置渐变色    
        Color[] color=new Color[4];    
        color[0]=new Color(Display.getCurrent(), 240, 240, 240);
//        color[1]=new Color(Display.getCurrent(), 0, 98, 255);   
        color[1]=Display.getCurrent().getSystemColor(SWT.COLOR_TITLE_BACKGROUND_GRADIENT);
        color[2]=Display.getCurrent().getSystemColor(SWT.COLOR_TITLE_BACKGROUND_GRADIENT);    
        color[3]=Display.getCurrent().getSystemColor(SWT.COLOR_TITLE_BACKGROUND_GRADIENT);      
        int[] intArray=new int[]{70,70,100};
        maincTabFolder.setSelectionBackground(color, intArray,true);    
		
		maincTabFolder.setSimple(false);//设置圆角   
		
		final CTabItem configTabItem = new CTabItem(maincTabFolder, SWT.CLOSE);
		configTabItem.setControl(configComposite);
		configTabItem.setText("    Config  ");
		maincTabFolder
				.addCTabFolder2Listener(new org.eclipse.swt.custom.CTabFolder2Adapter() {
					public void close(org.eclipse.swt.custom.CTabFolderEvent e) {
						  if (e.item == configTabItem) {
					          e.doit = false;
					        }
					}
				});
		
		
		maincTabFolder.setUnselectedCloseVisible(true);   
		maincTabFolder.setSelection(configTabItem);
	}
	
	private void showMainMenu() {
		Menu tmpMenu = new Menu(sShell, SWT.POP_UP);         //增加右键菜单
        tmpMenu.setVisible(true);              //menu必须设置成visible才能显示出 
        setAddBaseCodeMenuItem(tmpMenu);
        setCreateMastItem(tmpMenu);
	}
	
	private void setAddBaseCodeMenuItem(Menu tmpMenu)
	{
		 final String tabName = "AddBaseCodes";
		 MenuItem tmpItem = new MenuItem(tmpMenu, SWT.PUSH);
         tmpItem.setText("AddBaseCodes");          
         tmpItem.addSelectionListener(new SelectionListener() {
             
			@Override
			public void widgetDefaultSelected(SelectionEvent arg0) {
				System.out.println("DefaultSelected");
				
			}

			@Override
			public void widgetSelected(SelectionEvent arg0) {
				System.out.println("Selected");
				
				CTabItem item = getTabItem(tabName);
				AddBaseCodeCompsite cp= null ;
				if(item == null)
				{
					item = new CTabItem(maincTabFolder, SWT.None|SWT.MULTI|SWT.V_SCROLL);   
	                item.setText(tabName);   

	                cp=new AddBaseCodeCompsite(maincTabFolder, 0,sShell);
	                item.setControl(cp);
				}else
				{
					cp=(AddBaseCodeCompsite) item.getControl();
				}
				
				maincTabFolder.setSelection(item);
				
				cp.addSelectedItem(tableTree.getSelection());
			}
         });
	}
	
	private void setCreateMastItem(Menu tmpMenu)
	{
		 MenuItem tmpItem = new MenuItem(tmpMenu, SWT.PUSH);
         tmpItem.setText("Create Master");          
         tmpItem.addSelectionListener(new SelectionListener() {
             
			@Override
			public void widgetDefaultSelected(SelectionEvent arg0) {
				System.out.println("DefaultSelected");
				
			}

			@Override
			public void widgetSelected(SelectionEvent arg0) {
				CreateMasterForm cmForm=new CreateMasterForm(sShell,tableTree.getSelection());
				cmForm.open();
			}
         });
	}
	
	private CTabItem  getTabItem(String name)
	{
		CTabItem[] items = maincTabFolder.getItems();
		
		for(CTabItem item : items)
		{
			if(item.getText().equals(name))
			{
				return item;
			}
		}
		
		return null;
	}
	/**
	 * This method initializes configComposite	
	 *
	 */
	private void createConfigComposite() {
		configComposite = new Composite(maincTabFolder, SWT.NONE);
		createGroup1();
		configComposite.setLayout(null);
		createConfigGroup();
	}
	
	private void setControls() {
		this.editCtls.add(tableTree);
		this.editCtls.add(urlText);
		this.editCtls.add(userNameText);
		this.editCtls.add(passWordText);
		this.editCtls.add(saveDBConfigbutton);
		
	}
	private boolean setIsEditMode()
	{
		boolean isEdit=false;
		if(GlobalInfo.PRJ_NAME!=null && GlobalInfo.PRJ_NAME.trim().length()>0)
		{
			isEdit=true;
		}
		for(Control ctr: this.editCtls)
		{
			ctr.setEnabled(isEdit);
		}
		
		initPrjInfo();
		return isEdit;
	}
	
	public void initPrjInfo() {
		if(GlobalInfo.PRJ_NAME!=null && GlobalInfo.PRJ_NAME.trim().length()>0)
		{
			this.prjNametext.setText(GlobalInfo.PRJ_NAME);
			
			String[] connectInfo=PlugLogic.getConnectInfo();
			if(connectInfo!=null)
			{
				urlText.setText(connectInfo[0]);
				userNameText.setText(connectInfo[1]);
				passWordText.setText(connectInfo[2]);
				
				urlText.setEnabled(true);
				userNameText.setEnabled(true);
				passWordText.setEnabled(true);
				saveDBConfigbutton.setEnabled(true);
				importBaseButton.setEnabled(false);
			}
			else
			{
				urlText.setEnabled(false);
				userNameText.setEnabled(false);
				passWordText.setEnabled(false);
				saveDBConfigbutton.setEnabled(false);
				importBaseButton.setEnabled(true);
			}
		}
		else
		{
			clearPrjInfo();
		}
	}

	private void clearPrjInfo() {
		this.prjNametext.setText("");
		this.urlText.setText("");
		this.userNameText.setText("");
		this.passWordText.setText("");
		
	}

	/**
	 * This method initializes configGroup	
	 *
	 */
	private void createConfigGroup() {
		configGroup = new Group(configComposite, SWT.NONE);
		configGroup.setLayout(null);
		configGroup.setText("config");
		configGroup.setBounds(new Rectangle(7, 80, 707, 457));
		choosePRJButton = new Button(configGroup, SWT.NONE);
		choosePRJButton.setBounds(new Rectangle(452, 24, 114, 28));
		choosePRJButton.setText("Change");
		label = new Label(configGroup, SWT.NONE);
		label.setBounds(new Rectangle(18, 31, 94, 18));
		label.setText("Project Name :");
		prjNametext = new Text(configGroup, SWT.BORDER | SWT.READ_ONLY);
		prjNametext.setBounds(new Rectangle(119, 27, 321, 24));
		importBaseButton = new Button(configGroup, SWT.NONE);
		importBaseButton.setText("Import BaseCode");
		importBaseButton.setLocation(new Point(575, 24));
		importBaseButton.setSize(new Point(114, 28));
		label1 = new Label(configGroup, SWT.HORIZONTAL | SWT.SEPARATOR);
		label1.setBounds(new Rectangle(19, 61, 670, 18));
		label1.setText("Label");
		label2 = new Label(configGroup, SWT.NONE);
		label2.setBounds(new Rectangle(20, 93, 128, 18));
		label2.setText("DataBase Config :");
		label3 = new Label(configGroup, SWT.RIGHT);
		label3.setText("URL :");
		label3.setSize(new Point(90, 18));
		label3.setLocation(new Point(37, 122));
		label4 = new Label(configGroup, SWT.RIGHT);
		label4.setBounds(new Rectangle(36, 150, 90, 18));
		label4.setText("UserName :");
		label5 = new Label(configGroup, SWT.RIGHT);
		label5.setText("PassWord :");
		label5.setSize(new Point(90, 18));
		label5.setLocation(new Point(37, 180));
		urlText = new Text(configGroup, SWT.BORDER);
		urlText.setSize(new Point(523, 24));
		urlText.setLocation(new Point(140, 120));
		userNameText = new Text(configGroup, SWT.BORDER);
		userNameText.setLocation(new Point(140, 150));
		userNameText.setSize(new Point(523, 24));
		passWordText = new Text(configGroup, SWT.BORDER);
		passWordText.setLocation(new Point(140, 180));
		passWordText.setSize(new Point(523, 24));
		label11 = new Label(configGroup, SWT.HORIZONTAL | SWT.SEPARATOR);
		label11.setBounds(new Rectangle(17, 255, 679, 10));
		label11.setText("Label");
		saveDBConfigbutton = new Button(configGroup, SWT.NONE);
		saveDBConfigbutton.setBounds(new Rectangle(554, 218, 109, 28));
		saveDBConfigbutton.setText("Save DBConfig");
		saveDBConfigbutton
				.addSelectionListener(new org.eclipse.swt.events.SelectionAdapter() {
					public void widgetSelected(org.eclipse.swt.events.SelectionEvent e) {
						if(urlText.getText().length()>0
						   &&userNameText.getText().length()>0
						   &&passWordText.getText().length()>0)
						{
							PlugLogic.saveConnectInfo(new String[] {
									urlText.getText()
									,userNameText.getText()
									,passWordText.getText()
							});
							
							MessageBox dialog=new MessageBox(sShell,SWT.OK|SWT.ICON_INFORMATION);
					        dialog.setText("message");
					        dialog.setMessage("save complete!");
					        dialog.open();
						}
					}
				});
		importBaseButton
				.addSelectionListener(new org.eclipse.swt.events.SelectionAdapter() {
					public void widgetSelected(org.eclipse.swt.events.SelectionEvent e) {
						doImportBase();
					}
				});
		choosePRJButton
				.addSelectionListener(new org.eclipse.swt.events.SelectionAdapter() {
					public void widgetSelected(org.eclipse.swt.events.SelectionEvent e) {
						doChose();
					}
				});
	}

	protected void doImportBase() {
		if(GlobalInfo.PRJ_NAME==null||GlobalInfo.PRJ_NAME.length()==0)
		{
			doChose();
		}
		if(GlobalInfo.PRJ_NAME!=null)
		{
			 try {
					new ProgressMonitorDialog(sShell).run(true, true,
					        new ImportBaseOperation(MainForm.this));
				} catch (InvocationTargetException e1) {
					e1.printStackTrace();
				} catch (InterruptedException e1) {
					e1.printStackTrace();
				}
		}
	}
	
	protected void doChose() {
		String temp=GlobalInfo.PRJ_NAME;
		GlobalInfo.PRJ_NAME=null;
		FolderFromWorkspaceDialog fd = new FolderFromWorkspaceDialog(sShell);
		fd.setPrjOnly(true);
		Path pt = fd.openFolderSelectDialog();	
		if(pt!=null)
		{
			GlobalInfo.PRJ_NAME=pt.getDisplayPath().trim();
			this.prjNametext.setText(GlobalInfo.PRJ_NAME);
		}
		if(GlobalInfo.PRJ_NAME==null)
		{
			GlobalInfo.PRJ_NAME=temp;
		}
		
		setIsEditMode();
		
	}

	/**
	 * This method initializes bannerComposite	
	 *
	 */
	private void createBannerComposite() {
		GridLayout gridLayout1 = new GridLayout();
		gridLayout1.horizontalSpacing = 0;
		gridLayout1.marginWidth = 0;
		gridLayout1.verticalSpacing = 0;
		gridLayout1.numColumns = 2;
		gridLayout1.marginHeight = 0;
		GridData gridData1 = new GridData();
		gridData1.verticalSpan = 3;
		gridData1.grabExcessHorizontalSpace = true;
		gridData1.heightHint = 67;
		gridData1.horizontalAlignment = org.eclipse.swt.layout.GridData.FILL;
	
			Image bannerImage = PlugUILogic.getImage(sShell.getDisplay(),ImagePath.CONVJPPRJ_WIZ);
			//Image bannerImage = AbstractUIPlugin.imageDescriptorFromPlugin( GlobalInfo.PLUGIN_ID, ImagePath.CONVJPPRJ_WIZ).createImage();
			
			bannerComposite = new BannerComposite(sShell, SWT.NONE,bannerImage);


		
		bannerComposite.setLayoutData(gridData1);
		bannerComposite.setLayout(gridLayout1);
		bannerComposite.setBanTitle(GlobalInfo.PLUGIN_ID);
		bannerComposite.setBanInfo("Create basic code for project.      Version:1.0");
	}

	
	public Shell getsShell() {
		return sShell;
	}

	public static void main(String[] args) {
		MainForm form =new MainForm();
		form.openShell(null);
	}
}
